<?php

namespace App\Repositories\Eloquent\Exm;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;


use App\Repositories\Eloquent\Biz\TrackRepository as Track;
use App\Repositories\Eloquent\Biz\RecordRepository as Record;
use App\Repositories\Eloquent\Biz\SummaryRepository as Summary;
use DB;


use App\Repositories\Eloquent\Exm\QuizRepository as Quiz;

class WarehouseRepository extends Repository
{

    /**
     * @param App
     */

    protected $record, $track, $summary;

    protected $debug;

    public function __construct(App $app,Track $track, Record $record, Summary $summary,
                    Quiz $quiz)
    {
        parent::__construct($app);

        $this->track = $track;

        $this->record = $record;

        $this->summary = $summary;

        $this->quiz = $quiz;
        $this->debug = env('SMS_DEBUG');
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Exm\Warehouse';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($query = '')
    {
        $result = $this->model
                ->withCount('users','items')
                ->orderBy('id', 'asc');

        return $result;
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store($request)
    {
        $warehouse = $this->create([
            'name'      => $request->name,
            'type'      => is_null($request->type) ? 0:$request->type,
            'number'    => is_null($request->number) ? 5:$request->number,
            'sequence'    => is_null($request->sequence) ? 1:$request->sequence,
            'status'      => is_null($request->status) ? 0:$request->status,
        ]);

        if (!!$warehouse) {
             return $this->responseSuccess('增加答题活动成功', $warehouse, route('exam.index'));
        }

        return $this->responseFail(500,'增加答题活动失败');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $warehouse = $this->model->find($id);

        if (!$warehouse)
            return $this->responseFail(404, '活动信息不正确');

        return $warehouse;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function renew($request, $id)
    {
        $result = $this->update([
            'name'      => $request->name,
            'type'      => is_null($request->type) ? 0:$request->type,
            'number'    => is_null($request->number) ? 5:$request->number,
            'sequence'    => is_null($request->sequence) ? 1:$request->sequence,
            'status'      => is_null($request->status) ? 0:$request->status,
        ], $id);

        if (!!$result) {
             return $this->responseSuccess('修改答题活动成功');
        }

        return $this->responseFail(500,'修改答题活动失败');
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function setItems($request,$id)
    {
        $data = array();

        DB::beginTransaction();

        try{
            $result = DB::table('exm_items')
                ->where('warehouse_id', $id)
                ->delete();

            foreach($request->items as $item){
                $data[] = [
                    'warehouse_id'=>$id,
                    'question_id'=>$item
                ];
            }

            DB::table('exm_items')->insert($data);

            DB::commit();

            return $this->responseSuccess('题目设置成功', null, route('exam.item',$id));

        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500,'题目设置失败');
        }
    }


    public function activity()
    {
        return $this->model
            ->with('items','items.question')
            ->where('status', STATUS_NORMAL)
            ->orderBy('id', 'desc')->first();
    }


    public function setAnswer($user, $request)
    {
        $data = array();
        $correct = array();

        DB::beginTransaction();

        try{
            //答题用户
            $auser = new \App\Models\Exm\Auser;
            $auser->uid = $user->id;
            $auser->account = $user->account;
            $auser->warehouse_id = $request->id;
            $auser->type = $user->type;
            $auser->save();

            for($i=0;$i<5;$i++){
                $q = \App\Models\Exm\Question::find($request->question[$i]);
                $correct[] = $q->correct()->id;
            }
            //答题详情
            for($i=0;$i<5;$i++){
                $data[] = [
                    'uid'=>$user->id,
                    'account'=>$user->account,
                    'warehouse_id'=>$request->id,
                    'question_id'=>$request->question[$i],
                    'correct_id'=>$correct[$i],
                    'answer'=>$request->answer[$i],
                ];
            }

            DB::table('exm_answers')->insert($data);


            //2020.4.30增加答题送积分
                $activity = \App\Models\Mgt\Activity::nonCheck();

                $this->track->set($user, $activity, \App\Models\Biz\Track::TRACK_TYPE_EXTRA);

                //签到时，积分值默认为用户类型，阅读者1，志愿者2
                $point = $this->record->set($user, $activity, 2, \App\Models\Biz\Track::TRACK_TYPE_EXTRA);

                $this->summary->set($user, 3, $point);


            DB::commit();

            return $this->responseSuccess('答题成功，本次答题您将获得2积分奖励！', null, route('wx.index'));

        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500,'答题失败！');
        }
    }


    public function setQuiz($request)
    {
        if(!$this->debug){
            if($request->smscode != \Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确');
        }

        if( $this->quiz->isAttend( $request) )
            return $this->responseFail(405, '您已经参加过答题活动！');

        $result = $a = array();
        $data = array();
        $correct = array();

        DB::beginTransaction();

        try{
            //答题用户
            $auser = new \App\Models\Exm\Quiz;
            $auser->name = $request->name;
            $auser->idcard = $request->idcard;
            $auser->mobile = $request->mobile;
            $auser->region = $request->region;
            $auser->save();

            $answer = collect($request->answer)->transform(function ($item, $key) {
                $item = explode(",",$item);
                $result['question'] = $item[0];
                $result['answer'] = $item[1];
                return $result;
                /*list($k,$v) = explode(",",$item);
                $result[ $k ] = $v;
                return $item = $result;*/
            });

            $answer = $answer->values()->groupBy('question');
            foreach($answer as $key=>$ans){
                $a = $ans->map(function ($item, $k) {
                    //dd($item['answer']);
                    return $item['answer'];
                });
                $a = implode(",",$a->toArray());
                $data[] = [
                    'quiz_id'=>$auser->id,
                    'warehouse_id'=>$request->id,
                    'question_id'=>$key,
                    //'correct_id'=>$correct[$i],
                    'answer'=>$a,
                ];
            }


            DB::table('exm_ans')->insert($data);

            DB::commit();

            return $this->responseSuccess('答题成功！', null, route('wx.settle.quiz'));

        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500,'答题失败！');
        }
    }


    public function setResist($request)
    {
        if(!$this->debug){
            if($request->smscode != \Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确');
        }

        //身份证号码检测
        $idcard = $request->idcard;
        $birth = strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8);
        if( (int)$birth > 19661230)
            return $this->responseFail(405, '年龄不符合活动要求');

        if( $this->quiz->isAttend( $request) )
            return $this->responseFail(405, '您已经参加过答题活动！');

        $data = array();

        //检测答案
        $question = \App\Models\Exm\Question::find($request->question);

        if(!$question || !$this->checkAnswer($question,$request->answer))
            return $this->responseFail(405, '回答不正确</br>请重新作答或选择其它题目');

        DB::beginTransaction();

        try{
            //答题用户
            $auser = new \App\Models\Exm\Quiz;
            $auser->name = $request->name;
            $auser->idcard = $request->idcard;
            $auser->mobile = $request->mobile;
            $auser->region = $request->region;
            $auser->save();

            $data[] = [
                    'quiz_id'=>$auser->id,
                    'warehouse_id'=>$request->id,
                    'question_id'=>$request->question,
                    //'correct_id'=>$correct,
                    'answer'=>json_encode($request->answer),
                ];

            DB::table('exm_ans')->insert($data);

            //重置题库池状态，变为取消
            $item = \App\Models\Exm\Item::find($request->item);
            $item->status = STATUS_FREEZE;
            $item->save();

            DB::commit();

            return $this->responseSuccess('答题成功！', null, route('wx.settle.resist'));

        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500,'答题失败！');
        }
    }

    protected function checkAnswer($question,$answer)
    {
        $correct = $question->corrects()
                    ->pluck('id')
                    ->toArray();

        $diff = collect($answer)->diff($correct);

        if($diff->count() == 0)
            return true;

        return false;
    }
}